package com.myschool.server.manager.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myschool.server.dao.GradeDao;
import com.myschool.server.dao.SchoolDao;
import com.myschool.server.dao.SectionDao;
import com.myschool.server.dao.UserDao;
import com.myschool.server.dao.support.BaseEntityDaoHibernate;
import com.myschool.server.manager.BaseManager;
import com.myschool.server.manager.SectionManager;
import com.myschool.server.model.Grade;
import com.myschool.server.model.Section;
import com.myschool.server.model.Subject;
import com.myschool.server.model.User;

@Service
@Transactional
public class SectionManagerImpl extends BaseManager<Section> implements
		SectionManager {

	@Autowired
	private SectionDao dao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private SchoolDao schoolDao;

	@Autowired
	private GradeDao gradeDao;

	@Override
	protected BaseEntityDaoHibernate getDao() {

		return (BaseEntityDaoHibernate) dao;
	}

	public Set<Section> createSections(Long gradeId, Set<Section> sections) {

		Grade grade = this.gradeDao.get(gradeId);

		if (grade.getSections() != null && grade.getSections().size() > 0) {

			grade.getSections().addAll(sections);
		} else {

			grade.setSections(sections);
		}
		this.gradeDao.save(grade);
		return grade.getSections();
	}

	public Section assignTeacherToSection(Long sectionId, User teacher) {

		User classTeacher = this.userDao.get(teacher.getEntityId());

		Section section = this.dao.get(sectionId);
		section.setClassTeacher(classTeacher);
		this.dao.save(section);
		return section;
	}

	public void removeStudentFromSection(Long sectionId, User student) {
		User classStudent = this.userDao.get(student.getEntityId());

		classStudent.setSection(null);

		this.userDao.save(classStudent);

	}

	public Section addStudentsToSection(Long sectionId, Set<User> students) {

		Section section = this.dao.get(sectionId);

		if (section.getStudents() != null && section.getStudents().size() > 0) {

			section.getStudents().addAll(students);
		} else {
			section.setStudents(students);
		}
		this.dao.save(section);
		return section;
	}

	public Section addSubjectsToSection(Long sectionId, Set<Subject> subjects) {
		Section section = this.dao.get(sectionId);
		if (section.getSubjects() != null) {
			section.getSubjects().addAll(subjects);
		} else {

			section.setSubjects(subjects);
		}
		this.dao.save(section);
		return section;
	}
}
